package com.bilubi.reggie.reggie.service.Impl;

import com.bilubi.reggie.reggie.bean.AddressBook;
import com.bilubi.reggie.reggie.mapper.AddressBookMapper;
import com.bilubi.reggie.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> selectAddressBookByUserId(Long userId) {
        return addressBookMapper.selectByUserId(userId);
    }

    @Override
    public AddressBook selectAddressBookById(Long id) {
        return addressBookMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateAddressBook(AddressBook addressBook) {
        return addressBookMapper.updateByPrimaryKeySelective(addressBook);
    }

    @Override
    public int addAddressBook(AddressBook addressBook) {
        return addressBookMapper.insertSelective(addressBook);
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public int updateDefaultAddressBook(AddressBook addressBook) {
        addressBook.setIsDefault(0);
        addressBookMapper.deleteDefaultByUserId(addressBook);
        addressBook.setIsDefault(1);
        return addressBookMapper.updateByPrimaryKeySelective(addressBook);
    }

    @Override
    public AddressBook getDefaultAddressBook() {
        return addressBookMapper.selectDefaultByUserId(new AddressBook());
    }
}
